package com.itheima.app.controller;

import com.itheima.app.interceptor.UserHolder;
import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    UserManager userManager;

    @PostMapping("/user/save")
    public ResponseEntity save(@RequestBody User user){
        return userManager.save(user);
    }

    @GetMapping("/user/findByPhone")
    public ResponseEntity findByPhone(String phone){
        return userManager.findByPhone(phone);
    }

    @PostMapping("/user/login")
    public ResponseEntity sendCode(@RequestBody Map<String,String> map){
        //1.获取手机号
        String phone = map.get("phone");

        //2.调用manager完成发送操作
        return userManager.sendCode(phone);
    }

    @PostMapping(value = "/user/loginVerification")
    public ResponseEntity regAndLogin(@RequestBody Map<String,String> map){
        //1.获取手机号和验证码
        String phone = map.get("phone");
        String requestCode = map.get("verificationCode");

        //2.调用manager完成注册登陆操作
        return userManager.regAndLogin(phone,requestCode);
    }

    @PostMapping("/user/loginReginfo")
    public ResponseEntity saveUserInfo(@RequestBody UserInfo userInfo,@RequestHeader("Authorization") String token){
        return userManager.saveUserInfo(userInfo,token);
    }


    @PostMapping({"/user/loginReginfo/head","/users/header"})
    public ResponseEntity saveUserInfoHead(MultipartFile headPhoto,@RequestHeader("Authorization") String token) throws IOException {
        return userManager.saveUserInfoHead(headPhoto,token);
    }

    @GetMapping("/users")
    public ResponseEntity findUserInfoById(Long userID,Long huanxinID){
        //  如果userID不为空,就按照userID查询
        if (userID != null) {
            return userManager.findUserInfoById(userID);
        }
        //  如果userID为空,huanxinID不为空,就按照huanxinID查询
        if (huanxinID != null) {
            return userManager.findUserInfoById(huanxinID);
        }
        //  如果上面两个都为空,就从token中获取登录用户id查询
        User user = UserHolder.get();
        return userManager.findUserInfoById(user.getId());
    }

    @PutMapping("/users")
    public ResponseEntity updateUserInfo(@RequestBody UserInfo userInfo){
        return userManager.updateUserInfo(userInfo);
    }
}
